package com.ruoyi.stock2.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;

public class OtherUtils {
    private static final Logger log = LoggerFactory.getLogger(OtherUtils.class);
    public static String getLocalDateStr(Date date, String formatter) {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(formatter);
        Instant instant = date.toInstant();
        ZoneId zoneId = ZoneId.systemDefault();
        LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zoneId);
        String dateStr = dateTimeFormatter.format(localDateTime);

        return dateStr;
    }
    /**
     * 执行命令
     *
     * @param cmd
     * @throws IOException
     */
    public static void exec(String cmd) throws IOException, InterruptedException {
        long startTime = System.currentTimeMillis();
        log.warn("开始执行shell命令," + cmd);
        Process process = Runtime.getRuntime().exec(cmd);
        printMessage(process.getInputStream());
        printMessage(process.getErrorStream());
        if (process.waitFor() == 0) {
            log.warn("命令执行成功(总耗时:" + (System.currentTimeMillis() - startTime) / 1000 + "秒)");
        } else {
            log.warn("命令执行成功失败");
        }
    }

    /**
     * 读取流到控制台(防止死锁)
     *
     * @param input
     */
    private static void printMessage(final InputStream input) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Reader reader = new InputStreamReader(input, StandardCharsets.UTF_8);
                BufferedReader bf = new BufferedReader(reader);
                String line = null;
                try {
                    while ((line = bf.readLine()) != null) {
                        log.warn(line);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        input.close();
                    } catch (IOException e) {
                    }
                }

            }
        }).start();

    }



}
